package org.example;

import java.sql.*;
import java.text.MessageFormat;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: dings
 * Date: 2024-09-21
 * Time: 10:27
 */
public class Demo01_DriverManger {
    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            //1. 加载数据库厂商提供的驱动
            //通过完全限定名记载指定的类到JVM
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2. 获取数据库连接（物理连接）
            connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test2?characterEncoding=utf8&" +
                    "allowPublicKeyRetrieval=true&useSSL=false", "root", "111111");
            //3. 创建Statement对象
            statement = connection.createStatement();
            //4. 定义SQL并执行SQL语句
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入要查询的学生的姓名：");
            //接收用户输入
            String name = scanner.next();
            String sql = "select student_id, sn, name, mail, class_id from student where name = '" + name + "'";
            //5. 执行SQL并获取查询结果
            resultSet = statement.executeQuery(sql);
            //6. 遍历结果集并打印
            while (resultSet.next()) {
                long stuId = resultSet.getLong(1);
                String stuSn = resultSet.getString(2);
                String stuName = resultSet.getString(3);
                String stuMail = resultSet.getString(4);
                long stuClassId = resultSet.getLong(5);
                System.out.println(MessageFormat.format("学生编号={0}, 学号={1}, 姓名={2}, 邮箱={3}, 班级编号={4}",
                        stuId, stuSn, stuName, stuMail, stuClassId));
            }

        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }finally {
            if(resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}